package com.bidevalution.business.function;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

/**
 * 
 * @Description: 列表中，获取出现频率最高的元素
 * @author daizhifeng
 * @date 2019年9月19日 上午10:51:16
 * @version V2.0
 */
public class MaxFrequencyOfArrayFunction extends AbstractFunction {
	private FunctionInitializer functionInitializer;

	public MaxFrequencyOfArrayFunction(FunctionInitializer functionInitializer) {
		super();
		this.functionInitializer = functionInitializer;
	}
	/**
	 * 
	 * <p>Description: </p>
	 * @param env
	 * @param arg1 数组中
	 * @return 返回出现次数最多的值
	 * @see com.googlecode.aviator.runtime.function.AbstractFunction#call(java.util.Map, com.googlecode.aviator.runtime.type.AviatorObject)
	 */
	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
		String paramValue = FunctionUtils.getStringValue(arg1, env);
		List<String> elementList = new LinkedList<String>(Arrays.asList(paramValue.split(",")));
		Map<String, Integer> map = new HashMap<String, Integer>();
		for (String temp : elementList) {
			Integer count = map.get(temp.trim());
			map.put(temp.trim(), (count == null) ? 1 : count + 1);
		}
		StringBuilder stringBuilder = new StringBuilder();
		map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).findFirst()
				.ifPresent(entry -> {
					stringBuilder.append(entry.getKey());
				});
		return new AviatorString(stringBuilder.toString());
	}

	@Override
	public String getName() {
		return "maxFrequencyOfArray";
	}

}
